<template>
  <div class="wiper">
    <Filter title="数据字典" :items="filterItems" :model="filterModel"/>
    <Table :columns="columns" :data="data" :pagination="filterModel"/>
    <Form ref="form" v-model:show="show" :rules="rules" :model="formModel" :items="formItems">

    </Form>
  </div>
</template>
<script>
import Filter from "../../components/Filter";
import Table from "../../components/Table";
import Form from "../../components/Form";
import {
  ColumnProps, FilterItems, FilterModelProps, FormModel,
  RulesProps, FormItemsProps
} from "./config";
import {pager, allList, details, save, remove} from "../../api/dictionary"

export default {
  name: 'dictionary',
  data() {
    return {
      columns: ColumnProps,
      filterItems: FilterItems,
      filterModel: {
        ...FilterModelProps,
        onChange: (page, pageSize) => {
          this.filterModel.current = page;
          this.filterModel.pageSize = pageSize;
          this.load();
        }
      },
      data: [],
      show: false,
      rules: RulesProps,
      formModel: FormModel,
      formItems: FormItemsProps,
    }
  },
  components: {
    Filter,
    Table,
    Form
  },
  mounted() {
    this.load();
    this._allList();
  },
  methods: {

    add() {
      this._allList();
      this.formModel.id = "";
      this.$refs.form.resetField();
      this.show = true;
    },

    modify(ids) {
      this.show = true;
      details(ids.join(",")).then(res => {
        this.formModel = res.data;
      })
    },

    delete(ids) {
      return new Promise((resolve, reject) => {
        remove(ids.join(",")).then(res => {
          this.load();
          return resolve(res);
        }).catch(e => {
          return reject(e);
        })
      })
    },

    submit() {
      return new Promise((resolve, reject) => {
        save(this.formModel).then(res => {
          this.load();
          return resolve(res);
        }).catch((e) => {
          return reject(e)
        })
      })
    },

    load() {
      pager(this.filterModel).then(res => {
        this.data = res.data.rows;
        this.filterModel.total = res.data.total;
      })
    },

    _rename(data) {
      return data.length > 0 && data.map(item => {
        return {value: item.id, label: item.name}
      })
    },

    /**
     * 加载树形
     * @private
     */
    _allList() {
      allList().then(res => {
        this.formItems.filter(item => item.key === 'parentId')[0].data = this._rename(res.data);
      })
    }
  }
}
</script>
<style>

</style>
